var WastageProcessBoard = function () {
  var template = /* html */ `
    <div class="wastage-process-board" v-loading.fullscreen.lock="loading">
      <search-btns has-search ref="searchBtns" :pagination="pagination" :has-scroll="hasScrolling" search-btn-text="查询" :popover-width="250"
        search-title="查询条件" @after-leave="afterLeave" v-if="search!==null">
        <div slot="search">
          <template v-if="deptWorkName===null">
            <el-cascader clearable filterable v-model="search.deptWork" size="small" :options="deptWorkshopList" placeholder="部门-车间" separator="-"
              :props="deptWorkProps" style="width:180px"></el-cascader>
            <el-button size="small" type="primary" @click="searchData">查询</el-button>
          </template>
          <span v-else>部门-车间：{{deptWorkName}}</span>
        </div>
      </search-btns>

      <template v-if="isShow">
      <div class="wastage-process-board-content" v-if="search!==null" :key="pageId">
        <template v-for="(wastageList,rowIndex) in pageWastageList">
          <div :key="'wastageRow_'+rowIndex" :style="{height:'calc('+(100/rowNum)+'% - 3px)'}">
            <template v-for="(wastage,index) in wastageList">
              <wastage-process-item :key="'wastage_'+index" :wastage="wastage" :is-show="getHasShow(rowIndex)" :date-index="showStartDateIndex">
              </wastage-process-item>
            </template>
          </div>
        </template>
      </div>
      <div class="wastage-process-board-content" v-else>
        <div class="no-data">
          <div>用户没有设置车间无法查看工序能耗数据</div>
        </div>
      </div>
      </template>
    </div>
  `;

  return {
    mixins: [
      boardRunningMixin,
      boardMixin()
    ],

    watch: {
      'pagination.currentPage': function () {
        var pagination = this.pagination;
        var index = (pagination.currentPage - 1) * pagination.pageSize;

        var $content = $(this.$el).find('.wastage-process-board-content');
        var scrollTop = $content.scrollTop();
        var top = $content.find(`>div:eq(${index})`).position().top;
        scrollTop += top - 5;

        var self = this;
        this.hasScrolling = true;
        $content.animate({
          scrollTop: scrollTop
        }, 1000, function () {
          self.hasScrolling = false;
        });
      }
    },

    data: function () {
      return {
        loading: false,
        isShow: false,
        wastageList: [],
        searchWastageList: [],
        pageWastageList: [],
        search: null,
        oldSearch: null,
        pageId: SysUtil.getId(),
        deptWorkshopList: [],
        pagination: {
          currentPage: 1,
          totalCount: 0,
          pageSize: 2
        },
        rowNum: 2,
        colNum: 3,
        showStartDateIndex: 0,
        hasScrolling: false,
        deptWorkProps: {
          checkStrictly: true,
          value: 'id',
          label: 'name',
          children: 'workshops'
        }
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      this.setUser().then(function () {
        return self.setWastageList(true).then(function () {
          self.loading = false;
          self.isShow = true;
          if (self.search !== null) {
            self.setDeptWorkshopList();
            self.toSearchWastageList();
            self.toPageWastageList();
            self.boardRuning();
          }
        });
      }).catch(function () {
        self.loading = false;
        self.isShow = true;
      });
    },

    methods: {
      setUser: function () {
        var self = this;
        return SysUtil.getUser().then(function (user) {
          var deptWork;
          var permissionList = user.permissionList;
          var isManager = user.isManager;
          if (permissionList.indexOf('/superManager') !== -1) {
            isManager = 1;
          }

          var hasSelect = isManager === 1 || user.duty === '1';
          if (hasSelect) {
            deptWork = [];
          } else {
            var deptId = user.deptId;
            if (SysUtil.isEmpty(deptId) || deptId === '0') {
              return user;
            }
            deptWork = [`dept-${deptId}`];
            var workShopId = user.workShopId;
            if (!SysUtil.isEmpty(workShopId) && workShopId !== '0') {
              deptWork.push(`workshop-${workShopId}`);
            }
          }
          var search = {
            deptWork: deptWork
          };
          self.search = _.cloneDeep(search);
          self.oldSearch = _.cloneDeep(search);
          if (hasSelect) {
            return user;
          }
          return self.setDeptWorkName(deptWork, user);
        });
      },

      setWastageList: function (hasAlert) {
        var search = this.search;
        if (search === null) {
          this.wastageList = [];
          return Promise.resolve([]);
        }

        if (hasAlert === undefined) {
          hasAlert = false;
        }

        var self = this;
        return ajaxRequest("equipment/getProcessConsumptionData", {}, true, hasAlert).then(function (wastageList) {
          wastageList = _.map(wastageList, function (wastage) {
            wastage = new WastageProcessInfo(wastage);
            return wastage;
          });
          self.wastageList = wastageList;
          return wastageList;
        });
      },

      setDeptWorkshopList: function () {
        var wastageList = this.wastageList;
        var len = wastageList.length;
        var deptWorkshopMap = {};
        for (var i = 0; i < len; i++) {
          var wastage = wastageList[i];
          var deptId = wastage.deptId;
          if (SysUtil.isEmpty(deptId) || deptId === '0') {
            continue;
          }
          var deptWorkshop = deptWorkshopMap[deptId];
          if (deptWorkshop === undefined) {
            deptWorkshop = {
              id: `dept-${deptId}`,
              name: wastage.deptName,
              workshops: []
            };
            deptWorkshopMap[deptId] = deptWorkshop;
          }

          var workShopId = wastage.workShopId;
          if (SysUtil.isEmpty(workShopId) || workShopId === '0') {
            continue;
          }
          deptWorkshop.workshops.push({
            id: `workshop-${workShopId}`,
            name: wastage.workShopName
          });
        }

        var deptWorkshopList = [];
        for (var deptId in deptWorkshopMap) {
          var deptWorkshop = deptWorkshopMap[deptId];
          deptWorkshop.workshops = _.uniqBy(deptWorkshop.workshops, 'id');
          deptWorkshopList.push(deptWorkshop);
        }
        this.deptWorkshopList = deptWorkshopList;
      },

      searchData: function () {
        this.loading = true;

        this.clearTimeoutList();
        var self = this;
        setTimeout(function () {
          self.$refs['searchBtns'].closePopover();
          self.toSearchWastageList();
          self.toPageWastageList();
          self.pageId = SysUtil.getId();
          self.boardRuning();
          self.loading = false;
        }, 500);
      },

      toSearchWastageList: function () {
        var wastageList = this.wastageList;

        var deptWork = this.deptWork;
        if (deptWork !== null) {
          wastageList = _.filter(wastageList, function (wastage) {
            var dept = deptWork.dept;
            if (dept !== undefined) {
              if (wastage.deptId !== dept) {
                return false;
              }
            }
            var workshop = deptWork.workshop;
            if (workshop !== undefined) {
              if (wastage.workShopId !== workshop) {
                return false;
              }
            }
            return true;
          });
        }

        this.oldSearch = _.cloneDeep(this.search);
        this.searchWastageList = wastageList;
      },

      toPageWastageList: function () {
        var wastageList = this.searchWastageList;
        var pageWastages = [];
        var colNum = this.colNum;
        var rowNum = this.rowNum;
        var totalRow = wastageList.length / colNum;
        totalRow = _.round(totalRow, 1);
        totalRow = Math.ceil(totalRow / rowNum) * rowNum;

        for (var i = 0; i < totalRow; i++) {
          pageWastages.push([]);
        }

        var lastRow = 0;
        for (var i = 0; i < wastageList.length; i++) {
          var wastage = wastageList[i];
          var rowIndex = i / colNum;
          rowIndex = Math.floor(rowIndex);
          pageWastages[rowIndex].push(wastage);
          if (i === wastageList.length - 1) {
            lastRow = rowIndex;
          }
        }

        var lastWastage = pageWastages[lastRow];
        if (lastWastage.length > 0) {
          for (var i = lastWastage.length; i < colNum; i++) {
            lastWastage.push(null);
          }
        }

        this.pagination.totalCount = pageWastages.length;
        this.pageWastageList = pageWastages;
      },

      afterLeave: function () {
        this.search = _.cloneDeep(this.oldSearch);
      },

      getHasShow: function (rowIndex) {
        var pagination = this.pagination;
        var pageSize = pagination.pageSize;
        var startIndex = (pagination.currentPage - 1) * pageSize;
        return rowIndex >= startIndex && rowIndex < startIndex + pageSize;
      },

      boardRuning: function () {
        this.clearTimeoutList();
        this.setWastageDataRuning();
        this.resetWastageListRuning();
      },

      setWastageDataRuning: function () {
        var self = this;
        var timeout = setTimeout(function () {
          var showStartDateIndex = self.showStartDateIndex;
          showStartDateIndex++;
          var maxIndex = 20;
          if (showStartDateIndex > maxIndex) {
            showStartDateIndex = 0;
          }
          self.showStartDateIndex = showStartDateIndex;
          self.timeoutList[0] = null;
          self.setWastageDataRuning();
        }, 5000);
        this.timeoutList[0] = timeout;
      },

      resetWastageListRuning: function () {
        var tomorrowMoment = moment().add(1, 'day').startOf('day');
        var delayTime = tomorrowMoment.diff(moment());
        delayTime = Math.min(delayTime, 30 * 60 * 1000);
        var self = this;
        var timeout = setTimeout(function () {
          self.setWastageList().then(function () {
            self.setDeptWorkshopList();
            self.toSearchWastageList();
            self.toPageWastageList();

            var pagination = self.pagination;
            var totalPage = pagination.totalCount / pagination.pageSize;
            totalPage = Math.ceil(totalPage);
            if (pagination.currentPage > totalPage) {
              pagination.currentPage = 1;
            }
            self.pageId = SysUtil.getId();
            self.boardRuning();
          }).catch(function () {});
          self.timeoutList[1] = null;
        }, delayTime);
        this.timeoutList[1] = timeout;
      }
    },

    components: {
      SearchBtns: SearchBtns,
      WastageProcessItem: WastageProcessItem
    },

    template: template
  };
}();
